import React, { useState } from 'react';
import { useRitermConnection } from './hooks/useRitermConnection';
import { ConnectionForm } from './components/ConnectionForm';
import { TerminalXTerm } from './components/TerminalXTerm';
import { TerminalSession } from './types';

function App() {
  const {
    connectionState,
    isConnecting,
    error,
    connect,
    disconnect,
    createTerminal,
    sendTerminalInput,
    resizeTerminal,
    closeTerminal,
    renameTerminal,
    sendWebShare,
    sendWebUnshare,
  } = useRitermConnection();

  const [showCreateTerminal, setShowCreateTerminal] = useState(false);
  const [newTerminalName, setNewTerminalName] = useState('');

  const handleConnect = async (config: any) => {
    await connect(config);
  };

  const handleCreateTerminal = async () => {
    const sessionId = `terminal-${Date.now()}`;
    await createTerminal(sessionId, undefined, newTerminalName.trim() || undefined);
    setShowCreateTerminal(false);
    setNewTerminalName('');
  };

  const handleTerminalInput = (sessionId: string, data: number[]) => {
    console.log(`[Tauri Debug] handleTerminalInput called:`, {
      sessionId,
      dataLength: data.length,
      data: data.slice(0, 10) // Show first 10 bytes
    });
    sendTerminalInput(sessionId, data);
  };

  const handleTerminalResize = (sessionId: string, rows: number, cols: number) => {
    resizeTerminal(sessionId, rows, cols);
  };

  const handleTerminalClose = (sessionId: string) => {
    closeTerminal(sessionId);
  };

  const handleTerminalRename = (sessionId: string, newName?: string) => {
    renameTerminal(sessionId, newName);
  };

  // Show connection form if not connected
  if (!connectionState.isConnected) {
    return (
      <ConnectionForm
        onConnect={handleConnect}
        isConnecting={isConnecting}
        error={error}
      />
    );
  }

  return (
    <div className="min-h-screen bg-gray-900">
      {/* Header */}
      <header className="bg-gray-800 border-b border-gray-700">
        <div className="px-4 py-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <h1 className="text-xl font-bold text-white">Riterm</h1>
              <div className="flex items-center space-x-2">
                <div className="w-2 h-2 bg-green-500 rounded-full"></div>
                <span className="text-sm text-gray-300">Connected</span>
              </div>
              {connectionState.nodeId && (
                <span className="text-xs text-gray-500 font-mono">
                  {connectionState.nodeId.substring(0, 8)}...
                </span>
              )}
            </div>

            <div className="flex items-center space-x-4">
              <div className="text-sm text-gray-400">
                {connectionState.connectedTerminals.length} terminals
              </div>
              <div className="text-sm text-gray-400">
                {connectionState.peers.length} peers
              </div>
              <button
                onClick={disconnect}
                className="px-3 py-1 bg-red-600 hover:bg-red-700 text-white text-sm rounded transition-colors"
              >
                Disconnect
              </button>
            </div>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main className="p-4">
        <div className="mb-4 flex items-center justify-between">
          <div className="flex items-center space-x-4">
            <button
              onClick={() => setShowCreateTerminal(true)}
              className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded transition-colors"
            >
              Create Terminal
            </button>
          </div>

          {error && (
            <div className="text-sm text-red-400">
              Error: {error}
            </div>
          )}
        </div>

        {/* Create Terminal Modal */}
        {showCreateTerminal && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
            <div className="bg-gray-800 rounded-lg p-6 w-full max-w-md">
              <h3 className="text-lg font-semibold text-white mb-4">Create New Terminal</h3>

              <div className="space-y-4">
                <div>
                  <label htmlFor="terminalName" className="block text-sm font-medium text-gray-300 mb-1">
                    Terminal Name (Optional)
                  </label>
                  <input
                    id="terminalName"
                    type="text"
                    value={newTerminalName}
                    onChange={(e) => setNewTerminalName(e.target.value)}
                    placeholder="e.g., Development Terminal"
                    className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-md text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </div>

                <div className="flex space-x-3">
                  <button
                    onClick={handleCreateTerminal}
                    className="flex-1 bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-md transition-colors"
                  >
                    Create
                  </button>
                  <button
                    onClick={() => {
                      setShowCreateTerminal(false);
                      setNewTerminalName('');
                    }}
                    className="flex-1 bg-gray-600 hover:bg-gray-700 text-white font-medium py-2 px-4 rounded-md transition-colors"
                  >
                    Cancel
                  </button>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Terminals Grid */}
        {connectionState.connectedTerminals.length > 0 ? (
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
            {connectionState.connectedTerminals.map((terminal: TerminalSession) => (
              <TerminalXTerm
                key={terminal.sessionId}
                terminal={terminal}
                onInput={handleTerminalInput}
                onResize={handleTerminalResize}
                onClose={handleTerminalClose}
                onRename={handleTerminalRename}
              />
            ))}
          </div>
        ) : (
          <div className="text-center py-12">
            <div className="text-gray-400 mb-4">
              <svg className="w-16 h-16 mx-auto mb-4 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
              </svg>
              <h3 className="text-lg font-medium text-white mb-2">No Terminals Active</h3>
              <p className="text-sm">Create a terminal to start interacting with the remote CLI.</p>
            </div>
            <button
              onClick={() => setShowCreateTerminal(true)}
              className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded transition-colors"
            >
              Create Your First Terminal
            </button>
          </div>
        )}

        {/* Connected Peers */}
        {connectionState.peers.length > 0 && (
          <div className="mt-8 bg-gray-800 rounded-lg p-4">
            <h3 className="text-sm font-medium text-gray-300 mb-2">Connected Peers</h3>
            <div className="space-y-1">
              {connectionState.peers.map((peer, index) => (
                <div key={index} className="text-xs text-gray-400 font-mono">
                  {peer}
                </div>
              ))}
            </div>
          </div>
        )}
      </main>
    </div>
  );
}

export default App;
